﻿#include "Camerainit.h"

CameraInit::CameraInit(size_t height, size_t width, size_t pixel, QObject *parent)
    :m_ImageInfo(height,width, pixel)
{
    m_Buffer = dynamic_cast<Buffer*>(new ImageBuffer(5, m_ImageInfo));
    m_Thread = new CameraDataReadThread(m_Buffer);
    m_DeviceManger = new CyUSBDeviceManger;
    connect(m_DeviceManger, &CyUSBDeviceManger::RefreshUSBDevice, this, &CameraInit::DeviceRefresh);
    
    m_Thread->start();
}

void CameraInit::DeviceRefresh(DeviceStatus kind, QVector<USBDevice> *USBVector)
{
    qDebug() << "进入刷新界面";
    if(USBVector == nullptr) return ;
    switch(kind)
    {
    case DeviceStatus::In:
    {

    }
        break;
    case DeviceStatus::Out:
    {
        qDebug() << "运行到DeviceRefresh::Out方法处";
        if(m_CurrentDeviceName.isEmpty()) return;
        // 走到这里说明当前电脑接入了外部设备
        qDebug() << "hello";
        QVector<USBDevice>::iterator it = USBVector->begin();
        while(it != USBVector->end())
        {
            if(it->m_DeviceName == m_CurrentDeviceName) break;
        }
        qDebug() << (it == USBVector->end())  << " " << m_CurrentDeviceName;
        if(it == USBVector->end())
        {
            // 此时找不到对应设备名称，说明该设备已被拔出(此时应该修改m_CurrentDeviceName, 并使读取线程停止运行)
            this->CloseDevice();
            int i = -1;
            uint8_t in= -1;
            m_Thread->CurrentOpen(ParameterKind::Set, &i, &in);
            m_Thread->CloseCurrentDevice();
        }
    }
        break;
    }
    emit senderRefreshDevice(USBVector);
}

bool CameraInit::OpenDevice(QString DeviceName)
{
    int index = m_DeviceManger->NameToIndex(DeviceName);
    USBDevice* CurrentDevice = m_DeviceManger->NameToClass(DeviceName);

    // 当前待链接设备与原链接设备一致。直接返回true
    if (CurrentDevice->m_DeviceName == m_CurrentDeviceName) return true;

    if (index != -1 && CurrentDevice != nullptr)
    {
        // 此时获取到正确索引
        uint8_t tmpdata = CurrentDevice->m_InAddress;
        qDebug() << QString("m_InAddress值为: %1").arg(tmpdata);
        m_Thread->CurrentOpen(ParameterKind::Set, &index, &tmpdata);
        m_CurrentDeviceName = CurrentDevice->m_DeviceName;
        // qDebug() << "当前打开设备名称: " << m_CurrentDeviceName;
    }
    else if (index != -1 && CurrentDevice != nullptr && CurrentDevice->m_DeviceName != m_CurrentDeviceName)
    {
        // 当前待打开设备与当前已打开设备不一致(需要先关闭当前打开设备再链接待打开设备)
        m_Thread->CloseCurrentDevice();
        uint8_t tmpdata = CurrentDevice->m_InAddress;
        m_Thread->CurrentOpen(ParameterKind::Set, &index, &tmpdata);
        m_CurrentDeviceName = CurrentDevice->m_DeviceName;
    }
    else return false;
    return true;
}

bool CameraInit::CloseDevice()
{
    CameraDataReadThread::isRun = false;
    m_CurrentDeviceName.clear();
    return true;
}

bool CameraInit::FirstSelectDevice()
{
    if (m_DeviceManger == nullptr) return false;
    return m_DeviceManger->CheckDeviceCon();
}


